package com.itshen.service.impl;

import com.itshen.dto.ItemDTO;
import com.itshen.mapper.ItemMapper;
import com.itshen.result.Result;
import com.itshen.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class ItemServiceImpl implements ItemService {

    @Autowired
    ItemMapper itemMapper;
    @Override
    public List<ItemDTO> search() {
        return itemMapper.search();
    }

    @Override
    public ItemDTO getById(Long id) {
        return itemMapper.getById(id);
    }

    @Override
    public void updateById(ItemDTO item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public Result<String> deductInventory(Map<Long, Integer> itemIdNum) {
        AtomicInteger count= new AtomicInteger();
        itemIdNum.forEach((itemId, num) -> {
            count.addAndGet(itemMapper.updateNumByItemId(itemId, num));
        });
        if(count.get()==itemIdNum.size()){
            return Result.success("扣减库存成功");
        }else{
            throw new RuntimeException("扣减库存失败");
        }
    }
}
